﻿using System;
using System.Linq;
using System.Web.Mvc;
using MiniWeb.Core.Dtos;
using MiniWeb.Core.Entities;
using MiniWeb.Task;
using MiniWeb.Web.Controllers.Admin.ProductsInfoManager.ViewModels;
using WFramework.Extensions;
using WFramework.Mappers;
using WFramework.MvcPager;
using WFramework;
using System.Collections.Generic;
namespace MiniWeb.Web.Controllers.Admin.ProductsInfoManager
{

    public class ProductsInfoManagerController : BaseController
    {
        private readonly ProductsInfoTask _productsinfoTask = new ProductsInfoTask();
        private readonly ProductsClassTask _productsClassTask = new ProductsClassTask();
        private readonly ProductsTypeTask _productsTypeTask = new ProductsTypeTask();
        private readonly ProductsImgInfoTask _productsImgInfoTask = new ProductsImgInfoTask();

        public ActionResult List(int? rid, int? cid, int? pid,  DateTime? starttime, DateTime? endtime, int pageIndex = 1, int pageSize = 20,bool isSell=false, bool isChuXiao=false, bool isHot=false, bool isWeb=false)
        {
            ViewData["cid"] = cid;
            ViewData["typelist"] = _productsTypeTask.GetAll(100, "", null).ToSelectListForAll(c => c.ID.ToString(), c => c.TypeName);
            var pagedList = _productsinfoTask.GetPagedList(null,rid, cid, pid, isSell, isChuXiao, isHot, isWeb, starttime, endtime,null, pageIndex, pageSize);

            var model = new PagedList<ProductsInfoDto>(pagedList.ToList(), pageIndex, pageSize, pagedList.TotalItemCount);

            return View(model);
        }


        public ActionResult Save(int? id)
        {

            ViewData["typelist"] = _productsTypeTask.GetAll(100, "", null).ToSelectListForAll(c => c.ID.ToString(), c => c.TypeName);
            var model = new SaveProductsInfo();

            if (id != null)
            {
                var item = _productsinfoTask.GetById((int)id);
                if (item == null)
                    return AlertMsg("参数错误", HttpContext.Request.UrlReferrer.PathAndQuery);

                model = EntityMapper.Map<ProductsInfo, SaveProductsInfo>(item);
            }
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Save(SaveProductsInfo savemodel)
        {
            ViewData["typelist"] = _productsTypeTask.GetAll(100, "", null).ToSelectListForAll(c => c.ID.ToString(), c => c.TypeName);
            if (ModelState.IsValid)
            {
                string errMsg, savePath = string.Empty;
                var dict = new Dictionary<string, string>();
                if (savemodel.ID == null)
                {

                    foreach (var key in Request.Files.AllKeys)
                    {
                        if (Request.Files[key] == null || Request.Files[key].ContentLength == 0)
                        {
                            ModelState.AddModelError(key, "请上传");
                            return View(savemodel);
                        }

                        if (!UploadService.UploadFile(Request.Files[key], out savePath, out errMsg))
                        {
                            return AlertMsg(errMsg, HttpContext.Request.UrlReferrer.PathAndQuery);
                        }
                        dict.Add(key, savePath);
                    }

                    var model = new ProductsInfo
                    {
                        ProductImg = dict.ContainsKey("ProductImg") ? dict["ProductImg"] : "",
                        ProductName = savemodel.ProductName,
                        JianJie = savemodel.JianJie,
                        Price = savemodel.Price,
                        CPrice = savemodel.CPrice,
                        SellNum = savemodel.SellNum,
                        KuCunNum = savemodel.KuCunNum,
                        TotalNum = savemodel.TotalNum,
                        IsHot = savemodel.IsHot,
                        IsChuXiao = savemodel.IsChuXiao,
                        IsSell = savemodel.IsSell,
                        IsWeb = savemodel.IsWeb,
                        ProductsTypeID = savemodel.ProductsTypeID,
                        ProductsClassID = savemodel.ProductsClassID,
                        Des = savemodel.Des,
                        CreateDate = DateTime.Now,
                        Sort = savemodel.Sort,
                    };
                    _productsinfoTask.Add(model);
                }
                else
                {
                    var model = _productsinfoTask.GetById((int)savemodel.ID);

                    foreach (var key in Request.Files.AllKeys.Where(key => Request.Files[key] != null && Request.Files[key].ContentLength > 0))
                    {

                        if (!UploadService.UploadFile(Request.Files[key], out savePath, out errMsg))
                        {
                            return AlertMsg(errMsg, HttpContext.Request.UrlReferrer.PathAndQuery);
                        }
                        dict.Add(key, savePath);
                    }

                    if (model == null)
                        return AlertMsg("参数错误", HttpContext.Request.UrlReferrer.PathAndQuery);

                    model.ProductImg = dict.ContainsKey("ProductImg") ? dict["ProductImg"] : model.ProductImg;
                    model.ProductName = savemodel.ProductName;
                    model.JianJie = savemodel.JianJie;
                    model.Price = savemodel.Price;
                    model.CPrice = savemodel.CPrice;
                    model.SellNum = savemodel.SellNum;
                    model.KuCunNum = savemodel.KuCunNum;
                    model.TotalNum = savemodel.TotalNum;
                    model.IsHot = savemodel.IsHot;
                    model.IsChuXiao = savemodel.IsChuXiao;
                    model.IsSell = savemodel.IsSell;
                    model.IsWeb = savemodel.IsWeb;
                    model.ProductsTypeID = savemodel.ProductsTypeID;
                    model.ProductsClassID = savemodel.ProductsClassID;
                    model.Des = savemodel.Des;
                    model.CreateDate = DateTime.Now;
                    model.Sort = savemodel.Sort;
                    _productsinfoTask.Update(model);
                }
                return AlertMsg("保存成功", HttpContext.Request.UrlReferrer.PathAndQuery);

            }

            ////////////////////////////////////////


            return View(savemodel);
        }

        [HttpPost]
        public ActionResult peizhi(int pid)
        {

            var model = _productsinfoTask.GetById(pid);

            if (model.IsSell)
            {
                model.IsSell = false;
            }
            else
            {
                if (model.KuCunNum < 1)
                {
                    return Json(new { ret = false });
                }

                model.IsSell = true;

            }

            _productsinfoTask.Update(model);
            string msg = model.IsSell ? "上架" : "下架";
            return Json(new { ret= msg});
        }



        #region 删除用户信息 Delete

        [HttpPost]
        public void Delete(int id)
        {
            _productsinfoTask.Delete(id);
        }

        #endregion
    }
}